package com.suxin.thread.sync;

import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;

import java.util.concurrent.TimeUnit;

/**
 * @author Tang
 * @classname Sync1
 * @description [  ]
 * @date 2021/9/5 14:36
 */
public class Sync1 {

    public static void main(String[] args) throws Exception {
        TimeUnit.SECONDS.sleep(5);
        Object o = new Object();

        Thread thread1 = new Thread(() -> {
            synchronized (o) {
                System.out.println(ClassLayout.parseInstance(o).toPrintable());
                try {
                    TimeUnit.SECONDS.sleep(4);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized (o) {
                // 11101010 01001101 00111111 00011100 重量级锁
                System.out.println(ClassLayout.parseInstance(o).toPrintable());
                try {
                    TimeUnit.SECONDS.sleep(4);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();
        thread2.start();

        TimeUnit.SECONDS.sleep(6);
    }

    @Test
    public void test01() {
        // 00000001 00000000 00000000 00000000 无锁
        Object o = new Object();
        System.out.println("无锁模式:");
        System.out.println(ClassLayout.parseInstance(o).toPrintable());
        // 11001000 11100100 00100100 00000011 轻量级锁
        synchronized (o) {
            System.out.println(ClassLayout.parseInstance(o).toPrintable());
        }
    }

    @Test
    public void test02() throws Exception {
        // 偏向锁延迟 无锁状态 匿名偏向锁,可偏向状态
        // 00000101 00000000 00000000 00000000
        TimeUnit.SECONDS.sleep(5);
        Object o = new Object();
        System.out.println("无锁模式:");
        System.out.println(ClassLayout.parseInstance(o).toPrintable());
    }

    @Test
    public void test03() throws Exception {
        // 偏向锁延迟
        // 00000101 00100000 01110111 00000010 真正的偏向锁
        TimeUnit.SECONDS.sleep(5);
        Object o = new Object();
        System.out.println("有锁模式:");
        synchronized (o) {
            System.out.println(ClassLayout.parseInstance(o).toPrintable());
        }
    }

    @Test
    public void test04() throws Exception {

    }


}